<template>
  <div id="cyRequestTool" class="request-tool-container">
    <div class="tool-header">
      <h3 class="tool-title">网页请求工具</h3>
      <div class="method-tabs">
        <button
            v-for="method in requestMethods"
            :key="method"
            :class="['method-tab', { 'active': selectedMethod === method }]"
            @click="selectMethod(method)"
        >
          {{ method }}
        </button>
      </div>
    </div>

    <div class="request-form">
      <div class="form-group">
        <label class="form-label">请求URL</label>
        <div class="url-input-group">
          <select class="protocol-select" v-model="requestProtocol">
            <option value="https://">https://</option>
            <option value="http://">http://</option>
            <option value="ws://">ws://</option>
            <option value="wss://">wss://</option>
          </select>
          <input
              type="text"
              v-model="requestUrl"
              class="url-input"
              placeholder="输入请求地址"
              @keyup.enter="sendRequest"
          >
        </div>
      </div>

      <div class="form-row">
        <div class="form-group">
          <label class="form-label">请求头</label>
          <div class="editor-container">
            <textarea
                v-model="requestHeaders"
                class="code-editor"
                placeholder='{"Content-Type": "application/json"}'
            ></textarea>
          </div>
        </div>

        <div class="form-group" v-if="showRequestBody">
          <label class="form-label">请求体</label>
          <div class="editor-container">
            <textarea
                v-model="requestBody"
                class="code-editor"
                placeholder='{"key": "value"}'
            ></textarea>
          </div>
        </div>
      </div>

      <div class="form-group">
        <label class="form-label">超时时间 (ms)</label>
        <input
            type="number"
            v-model.number="timeout"
            min="0"
            max="60000"
            class="timeout-input"
        >
      </div>
    </div>

    <div class="tool-footer">
      <button class="btn secondary" @click="resetForm">
        <i class="icon-reset"></i> 重置
      </button>
      <button
          class="btn primary"
          @click="sendRequest"
          :disabled="isRequesting"
      >
        <i class="icon-send"></i> {{ isRequesting ? '请求中...' : '发送请求' }}
      </button>
    </div>

    <div class="response-container" v-if="responseData">
      <div class="response-header">
        <h4 class="response-title">响应结果</h4>
        <div class="response-meta">
          <span class="status-badge" :class="statusClass">
            {{ responseData.status }} {{ responseData.statusText }}
          </span>
          <span class="time-info">{{ responseData.time }}ms</span>
          <button class="btn small" @click="copyResponse">
            <i class="icon-copy"></i> 复制
          </button>
        </div>
      </div>

      <div class="response-tabs">
        <button
            v-for="tab in responseTabs"
            :key="tab"
            :class="['response-tab', { 'active': activeResponseTab === tab }]"
            @click="activeResponseTab = tab"
        >
          {{ tab }}
        </button>
      </div>

      <div class="response-content">
        <pre v-if="activeResponseTab === 'Preview' && isJson">{{ formattedResponse }}</pre>
        <pre v-else-if="activeResponseTab === 'Preview'">{{ responseData.data }}</pre>
        <pre v-else-if="activeResponseTab === 'Headers'">{{ formattedHeaders }}</pre>
        <pre v-else>{{ responseData.data }}</pre>
      </div>
    </div>

    <div class="error-container" v-if="errorData">
      <div class="error-header">
        <h4 class="error-title">请求错误</h4>
        <button class="btn small danger" @click="copyError">
          <i class="icon-copy"></i> 复制错误
        </button>
      </div>
      <div class="error-content">
        <pre>{{ errorData }}</pre>
      </div>
    </div>
  </div>
</template>
<script>
import { ref, computed, watch } from 'vue'

export default {
  setup() {
    // 请求配置
    const requestMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD']
    const selectedMethod = ref('GET')
    const requestProtocol = ref('https://')
    const requestUrl = ref('')
    const requestHeaders = ref('{\n  "Content-Type": "application/json"\n}')
    const requestBody = ref('{\n  "key": "value"\n}')
    const timeout = ref(5000)

    // 响应状态
    const isRequesting = ref(false)
    const responseData = ref(null)
    const errorData = ref(null)

    // 响应视图
    const responseTabs = ref(['Preview', 'Raw', 'Headers'])
    const activeResponseTab = ref('Preview')

    // 计算属性
    const showRequestBody = computed(() => {
      return ['POST', 'PUT', 'PATCH'].includes(selectedMethod.value)
    })

    const isJson = computed(() => {
      if (!responseData.value) return false
      try {
        JSON.parse(responseData.value.data)
        return true
      } catch {
        return false
      }
    })

    const formattedResponse = computed(() => {
      try {
        return JSON.stringify(JSON.parse(responseData.value.data), null, 2)
      } catch {
        return responseData.value.data
      }
    })

    const formattedHeaders = computed(() => {
      if (!responseData.value?.headers) return 'No headers available'
      return Object.entries(responseData.value.headers)
          .map(([key, value]) => `${key}: ${value}`)
          .join('\n')
    })

    const statusClass = computed(() => {
      if (!responseData.value) return ''
      const status = responseData.value.status
      if (status >= 200 && status < 300) return 'success'
      if (status >= 300 && status < 400) return 'redirect'
      if (status >= 400 && status < 500) return 'client-error'
      if (status >= 500) return 'server-error'
      return ''
    })

    // 方法
    const selectMethod = (method) => {
      selectedMethod.value = method
    }

    const sendRequest = async () => {
      if (!requestUrl.value || isRequesting.value) return

      isRequesting.value = true
      responseData.value = null
      errorData.value = null

      const startTime = Date.now()
      const url = requestProtocol.value + requestUrl.value

      try {
        // 解析请求头
        let headers = {}
        try {
          headers = JSON.parse(requestHeaders.value)
        } catch (e) {
          console.warn('Invalid headers JSON, using empty headers')
        }

        // 处理请求体
        let body = null
        if (showRequestBody.value && requestBody.value) {
          try {
            body = JSON.parse(requestBody.value)
          } catch (e) {
            body = requestBody.value
          }
        }

        // 处理GET请求参数
        let finalUrl = url
        if (selectedMethod.value === 'GET' && body && typeof body === 'object') {
          const params = new URLSearchParams()
          for (const [key, value] of Object.entries(body)) {
            params.append(key, value)
          }
          finalUrl += (url.includes('?') ? '&' : '?') + params.toString()
          body = null
        }

        // 发送请求
        const controller = new AbortController()
        const timeoutId = setTimeout(() => controller.abort(), timeout.value)

        const response = await fetch(finalUrl, {
          method: selectedMethod.value,
          headers,
          body: body ? JSON.stringify(body) : null,
          signal: controller.signal
        })

        clearTimeout(timeoutId)

        // 处理响应
        const data = await response.text()
        const responseHeaders = {}
        response.headers.forEach((value, key) => {
          responseHeaders[key] = value
        })

        responseData.value = {
          status: response.status,
          statusText: response.statusText,
          headers: responseHeaders,
          data,
          time: Date.now() - startTime
        }
      } catch (error) {
        errorData.value = {
          message: error.message,
          stack: error.stack,
          time: Date.now() - startTime
        }
      } finally {
        isRequesting.value = false
      }
    }

    const resetForm = () => {
      selectedMethod.value = 'GET'
      requestProtocol.value = 'https://'
      requestUrl.value = ''
      requestHeaders.value = '{\n  "Content-Type": "application/json"\n}'
      requestBody.value = '{\n  "key": "value"\n}'
      timeout.value = 5000
      responseData.value = null
      errorData.value = null
    }

    const copyResponse = () => {
      if (!responseData.value) return
      const text = activeResponseTab.value === 'Headers'
          ? formattedHeaders.value
          : activeResponseTab.value === 'Preview' && isJson.value
              ? formattedResponse.value
              : responseData.value.data
      copyToClipboard(text)
    }

    const copyError = () => {
      if (!errorData.value) return
      copyToClipboard(JSON.stringify(errorData.value, null, 2))
    }

    const copyToClipboard = (text) => {
      navigator.clipboard.writeText(text)
          .then(() => {
            alert('已复制到剪贴板')
          })
          .catch(err => {
            console.error('复制失败:', err)
            // 降级方案
            const textarea = document.createElement('textarea')
            textarea.value = text
            document.body.appendChild(textarea)
            textarea.select()
            document.execCommand('copy')
            document.body.removeChild(textarea)
            alert('已复制到剪贴板')
          })
    }

    // 监听请求方法变化
    watch(selectedMethod, (newVal) => {
      if (newVal === 'GET') {
        requestBody.value = ''
      }
    })

    return {
      // 数据
      requestMethods,
      selectedMethod,
      requestProtocol,
      requestUrl,
      requestHeaders,
      requestBody,
      timeout,
      isRequesting,
      responseData,
      errorData,
      responseTabs,
      activeResponseTab,

      // 计算属性
      showRequestBody,
      isJson,
      formattedResponse,
      formattedHeaders,
      statusClass,

      // 方法
      selectMethod,
      sendRequest,
      resetForm,
      copyResponse,
      copyError
    }
  }
}
</script>
<style scoped>
.request-tool-container {
  --primary-color: #00ff87;
  --secondary-color: #ff1f71;
  --accent-color: #60efff;
  --bg-dark: rgba(10, 20, 30, 0.95);
  --bg-light: rgba(255, 255, 255, 0.1);
  --text-primary: rgba(255, 255, 255, 0.9);
  --text-secondary: rgba(255, 255, 255, 0.7);
  --border-color: rgba(255, 255, 255, 0.2);
  --success-color: #00ff87;
  --redirect-color: #ffd700;
  --client-error-color: #ff8c00;
  --server-error-color: #ff1f71;
  --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

  background: var(--bg-dark);
  border-radius: 12px;
  border: 1px solid var(--border-color);
  box-shadow: 0 0 30px rgba(0, 0, 0, 0.5);
  color: var(--text-primary);
  font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
  overflow: hidden;
}

.tool-header {
  padding: 15px 20px;
  background: rgba(0, 0, 0, 0.3);
  border-bottom: 1px solid var(--border-color);
}

.tool-title {
  margin: 0 0 10px 0;
  font-size: 1.25rem;
  font-weight: 600;
  background: linear-gradient(135deg, var(--accent-color) 0%, var(--primary-color) 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.method-tabs {
  display: flex;
  gap: 5px;
  margin-top: 15px;
}

.method-tab {
  padding: 6px 12px;
  background: var(--bg-light);
  border: 1px solid var(--border-color);
  border-radius: 4px;
  color: var(--text-secondary);
  font-size: 0.85rem;
  font-weight: 600;
  cursor: pointer;
  transition: var(--transition);
}

.method-tab:hover {
  background: rgba(255, 255, 255, 0.15);
}

.method-tab.active {
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--accent-color) 100%);
  color: #111;
  border-color: transparent;
}

.request-form {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-row {
  display: flex;
  gap: 20px;
}

.form-row .form-group {
  flex: 1;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-size: 0.9rem;
  color: var(--text-secondary);
}

.url-input-group {
  display: flex;
}

.protocol-select {
  width: 100px;
  padding: 10px;
  background: var(--bg-light);
  border: 1px solid var(--border-color);
  border-radius: 6px 0 0 6px;
  color: var(--text-primary);
  font-family: inherit;
  border-right: none;
}

.url-input {
  flex: 1;
  padding: 10px 15px;
  background: var(--bg-light);
  border: 1px solid var(--border-color);
  border-radius: 0 6px 6px 0;
  color: var(--text-primary);
  font-family: inherit;
}

.timeout-input {
  width: 100px;
  padding: 10px 15px;
  background: var(--bg-light);
  border: 1px solid var(--border-color);
  border-radius: 6px;
  color: var(--text-primary);
  font-family: inherit;
}

.editor-container {
  height: 150px;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  overflow: hidden;
}

.code-editor {
  width: 100%;
  height: 100%;
  padding: 10px;
  background: rgba(0, 0, 0, 0.3);
  border: none;
  color: var(--text-primary);
  font-family: 'Fira Code', monospace;
  resize: none;
  tab-size: 2;
}

.code-editor:focus {
  outline: none;
}

.tool-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 15px 20px;
  background: rgba(0, 0, 0, 0.3);
  border-top: 1px solid var(--border-color);
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-family: inherit;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: var(--transition);
}

.btn.primary {
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--accent-color) 100%);
  color: #111;
}

.btn.secondary {
  background: var(--bg-light);
  color: var(--text-primary);
}

.btn.small {
  padding: 4px 8px;
  font-size: 0.8rem;
}

.btn.danger {
  background: linear-gradient(135deg, var(--secondary-color) 0%, #a020f0 100%);
  color: white;
}

.btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none !important;
  box-shadow: none !important;
}

.response-container,
.error-container {
  margin: 0 20px 20px;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  overflow: hidden;
}

.response-header,
.error-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 15px;
  background: rgba(0, 0, 0, 0.3);
  border-bottom: 1px solid var(--border-color);
}

.response-title,
.error-title {
  margin: 0;
  font-size: 1rem;
  color: var(--text-primary);
}

.response-meta {
  display: flex;
  align-items: center;
  gap: 10px;
}

.status-badge {
  padding: 3px 8px;
  border-radius: 12px;
  font-size: 0.8rem;
  font-weight: 600;
}

.status-badge.success {
  background-color: var(--success-color);
  color: #111;
}

.status-badge.redirect {
  background-color: var(--redirect-color);
  color: #111;
}

.status-badge.client-error {
  background-color: var(--client-error-color);
  color: #111;
}

.status-badge.server-error {
  background-color: var(--server-error-color);
  color: white;
}

.time-info {
  font-size: 0.8rem;
  color: var(--text-secondary);
}

.response-tabs {
  display: flex;
  border-bottom: 1px solid var(--border-color);
}

.response-tab {
  padding: 8px 15px;
  background: none;
  border: none;
  color: var(--text-secondary);
  font-size: 0.85rem;
  cursor: pointer;
  transition: var(--transition);
  border-bottom: 2px solid transparent;
}

.response-tab:hover {
  color: var(--text-primary);
}

.response-tab.active {
  color: var(--primary-color);
  border-bottom-color: var(--primary-color);
}

.response-content,
.error-content {
  max-height: 300px;
  overflow-y: auto;
  padding: 15px;
  background: rgba(0, 0, 0, 0.3);
}

pre {
  margin: 0;
  white-space: pre-wrap;
  word-break: break-word;
  font-family: 'Fira Code', monospace;
  font-size: 0.9rem;
  line-height: 1.5;
}

.error-content pre {
  color: var(--secondary-color);
}

.icon-reset,
.icon-send,
.icon-copy {
  display: inline-block;
  width: 16px;
  height: 16px;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

.icon-reset {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%23ffffff'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15' /%3E%3C/svg%3E");
}

.icon-send {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%23111'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M12 19l9 2-9-18-9 18 9-2zm0 0v-8' /%3E%3C/svg%3E");
}

.icon-copy {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%23ffffff'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3' /%3E%3C/svg%3E");
}

/* 滚动条样式 */
.response-content::-webkit-scrollbar,
.error-content::-webkit-scrollbar,
.code-editor::-webkit-scrollbar {
  width: 8px;
}

.response-content::-webkit-scrollbar-track,
.error-content::-webkit-scrollbar-track,
.code-editor::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 4px;
}

.response-content::-webkit-scrollbar-thumb,
.error-content::-webkit-scrollbar-thumb,
.code-editor::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 4px;
}

.response-content::-webkit-scrollbar-thumb:hover,
.error-content::-webkit-scrollbar-thumb:hover,
.code-editor::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.3);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .form-row {
    flex-direction: column;
    gap: 15px;
  }

  .response-tabs {
    overflow-x: auto;
  }

  .response-content,
  .error-content {
    max-height: 200px;
  }
}
</style>
